import java.util.*;

/**
 * @author LKQ
 * @date 2022/5/29 10:08
 * @description 二分查找
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] mat = {{1, 10, 10}, {1, 4, 5}, {2, 3, 6}};
        solution.kthSmallest(mat, 7);
    }

    public int kthSmallest(int[][] mat, int k) {
        int m = mat.length, n = mat[0].length;
        int left = 0, right = 0;
        // 计算第一列的和作为left，数组最小和,计算最后一列的和作为right，数组最大和
        for (int i = 0; i < m; ++i) {
            left += mat[i][0];
            right += mat[i][n - 1];
        }
        //二分法
        int initSum = left;
        while (left < right) {
            // 数组的和
            int mid = left + (right - left) / 2;
            // 计算数组的和小于mid有多少个
            int count = countLEMid(mat, mid, initSum, 0, k);
            if (count >= k) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;


    }

    public int countLEMid(int[][] mat, int mid, int lastSum, int rowIndex, int k) {
        int m = mat.length, n = mat[0].length;
        if (rowIndex == m) return 1;
        int count = 0;

        for (int col = 0; col < n; ++col) {
            int nextSum = lastSum - mat[rowIndex][0] + mat[rowIndex][col];
            if (nextSum <= mid) {
                //这一行的结果<=mid  可以往下走
                count += countLEMid(mat, mid, nextSum, rowIndex + 1, k);
                if (count >= k) return count;
            } else {
                break;
            }
        }
        return count;
    }
}
